import React, {Component} from 'react';
import './index.less';
import {base, high, toast} from 'nc-lightapp-front';
import Header from "../components/Header";
import updateButtonStatus from "./functions/updateButtonStatus";
import TableInfo from "../components/TableInfo";
import {getLangCode} from "../../../../public/functions/unit";
import {THEME} from "../../../../public/theme/theme";
import NCUploader from 'uap/common/components/NCUploader';
import SettingModal from '../components/SettingModal';
import WpsinitModal from '../components/wpsinitModal';
import wpsPreStatus from '../components/Header/functions/wpsPreStatus';
import WpsInitDesign from '../components/Header/functions/wpsDesignInitData';
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import {openRevision} from "../components/Header/functions/wpsinvode";
class BasicArchiveBase extends Component {
    constructor(props) {
        super(props);
        props.use.editTable('template', 'conditionList')
        props.use.form('conditionCard', 'folder')
        this.config = {
            pagecode: props.pagecode,
            appcode: props.appcode
        };
        this.state = {
            json: {},
            pkOrg: {}, // 新增合同模板时  table 创建组织对象
            showUploader: false, // 文件管理

            pk_conmodel: null, // 合同主键

            editting: false, //编辑态
            selectedRow: null,
            preSettingVisible: false,
            isNeedWpsInterview: false, // 是否弹出wps配置须知
            originUrl: '',
            wpsvisible: false
        };

    }
    initWpsConfig(url){
        wpsPreStatus({
            checkstatus:true,
            url:url
        }).then((res) => {
                if(res.success){
                    this.setState({
                        originUrl: url,
                        isNeedWpsInterview: res.data.readstatus
                    });
                }
               
            });
    }
    /**
     * 页面初始化
     */
    pageInit() {
        this.initUIDom();
    }

    initUIDom() {
        this.props.createUIDom(this.config, (data) => {
            let pkOrg = {};
            if (this.props.nodeName === 'GLOBAL') {
                pkOrg = {
                    display: this.state.json['cm6011-000007'], // 全局
                    value: 'GLOBLE00000000000000',
                }
            } else if (this.props.nodeName === 'GROUP') {
                pkOrg = {
                    display: this.props.groupName,
                    value: this.props.groupId,
                }
            } else if (this.props.nodeName === 'ORG') {
                pkOrg = {
                    display: this.state.pkOrg.display || null,
                    value: this.state.pkOrg.value || null,
                }
            }
            this.setState({
                queryOid: data.template.pageid,
                buttons: data.button || [],
                context: data.context || {},
                pkOrg
            });
            this.tableAddOpr(data.template["template"]);
            this.props.meta.setMeta(data && data.template ? data.template : {});
            this.props.button.setButtons(data && data.button ? data.button : {});
            const url = window.location.origin
            this.initWpsConfig(url)
            // 初始化按钮
            this.updateButtonStatus();
            // 加载table列表
            this.getTableInfo();
        });
    }

    /**
     * 表格添加操作列
     */
    tableAddOpr(tabledata) {
        let _this = this;
        let lang = getLangCode();
        let eventWidth = lang === 'english' ? 350 : 300;
        let oprWidth = lang === 'english' ? 120 : 110; 
        //添加表格操作列
        let event = {
            label: this.state.json["cm6011-000064"],
            attrcode: 'opr',
            itemtype: 'customer',
            //className: "table-opr",
            fixed: 'right',
            width: eventWidth + 'px',
            visible: true,
            render(text, record, index) {
                return (
                    <div className="currency-opr-col">
                        {_this.props.button.createOprationButton( 
                            ['add_body','templateSetting', 'copy', 'delete', 'export'],
                            {  
                                area: 'body',
                                onButtonClick: (props, id, e) => {
                                    _this.headerNode.onBtnOperation(props, id, 'body', record, index)
                                },
                                popContainer: document.querySelector('.header2')
                            }
                        )}
                    </div>
                );
            }
        };

        // 附件管理
        let fileCol = {
            attrcode: 'file',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: this.state.json['cm6011-000146'], /* 国际化处理： 附件管理*/
            width: oprWidth + 'px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                let billId = record.values.pk_conmodel.value;
                return (
                    <a style={{cursor: 'pointer'}}>
                        <i className="icon iconfont icon-fujianshenpi" onClick={(eve) => {
                            _this.setState({
                                showUploader: true,
                                pk_conmodel: billId
                            })
                        }}/>
                    </a>
                )
            }
        };
        tabledata.items.push(fileCol);
        tabledata.items.push(event);
    }

    componentWillMount() {
        let callback = (json, status, inlt) => {
            if (status) {
                this.setState({json, inlt}) // 保存json和inlt到页面state中并刷新页面
            }
        };
        this.props.MultiInit.getMultiLang({moduleId: 'cm6011', domainName: 'hrcm', callback})
    }

    componentDidMount() {
        if (window.location.href.match(/(localhost|127\.0\.0\.1):3006/)) window.location.hash = `ifr?page=2019`;
        if (!('remove' in Element.prototype)) {
            Element.prototype.remove = function () {
                if (this.parentNode) {
                    this.parentNode.removeChild(this);
                }
            };
        }
        this.pageInit();
    }

    updateState = (data, callback = () => {
    }) => {
        this.setState(data, callback)
    };

    updateButtonStatus = () => {
        updateButtonStatus.call(this);
    };

    // 附件的关闭点击
    onHideUploader = () => {
        this.setState({
            showUploader: false,
            groupLists: []
        })
    };

    //获取当前附件列表
    getGroupList = (list) => {
        //要在state里面顶一个变量，用来存储列表数组
        this.setState({
            groupLists: list
        })
    };

    beforeUpload(billId, fullPath, file, fileList) {
        // 参数：单据id，当前选中分组path、当前上传文件对象，当前文件列表

        // const isJPG = file.type === 'image/jpeg';
        //
        // const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //     /* 国际化处理： 上传大小小于2M*/
        // }
        // return isJPG && isLt2M;
        return true
        // 备注： return false 不执行上传  return true 执行上传
    }

    /**
     * 获取table数据
     */
    getTableInfo = (callback) => {
        this.tableInfo.getTableInfo(callback);
    };

    refresh = (callback) => {
        //获取 table数据
        this.getTableInfo(callback);
    };

    onClose = () => {
        this.setState({preSettingVisible: false})
    }
    closeWpsModal = () => {
        this.setState({wpsvisible: false})
    }
    //当wps配置完成时打开wps
    confirmOpenWps = () => {
        const {selectedRow} = this.state;
        let pk_conmodel = selectedRow.values.pk_conmodel.value;
        let pk_org = this.state.pkOrg.value;
        WpsInitDesign(pk_conmodel, pk_org).then(res => {
            if (res.success && res.data) {
                console.log("模板设置返回的数据",res.data)
                let result = deepCopy(res.data)
                result.pk_rpt_def =  pk_conmodel;
                result.pk_conmodel = pk_conmodel;
                openRevision(result)
                // console.log("当前行数据",record.values)
                this.closeWpsModal()
            }
        })
    }
    copySure = () => {
        const {
            json
        } = this.state;
        toast({
            color: 'success',
            content: '复制成功' // '复制成功'
        });
    }
    render() {
        const {
            showUploader,
            json,
            editting,
            pkOrg,
            pk_conmodel,
            preSettingVisible,
            selectedRow,
            isNeedWpsInterview,
            originUrl,
            wpsvisible
        } = this.state;
        const componentProps = {
            ...this.props,
            json,
            editting,
            pkOrg,
            pk_conmodel,
            isNeedWpsInterview,
            originUrl,
            updateState: this.updateState,
            refresh: this.refresh,
            updateButtonStatus: this.updateButtonStatus,
        };
        return (

            <div className={`postseq-base ${THEME.bgCommon}`}>

                {/* file */}
                <div className="nc-faith-demo-div2">
                    {/* 这里是附件上传组件的使用，需要传入三个参数 */}
                    {showUploader && <NCUploader
                        disableDownload={false}
                        billId={this.state.pk_conmodel}
                        // billNo={'true'} // 可选  此字段决定了左侧是否显示billNo
                        // target={target}
                        customize={{uploadTrpe: '0'}}
                        placement={'bottom'}
                        getGroupList={this.getGroupList}
                        uploadTitle={this.state.json['cm6011-000062']}/* 国际化处理： 附件管理*/
                        onHide={this.onHideUploader} // 关闭功能
                        beforeUpload={this.beforeUpload}/>
                    }
                </div>

                <Header
                    {...componentProps}
                    selectedRow={selectedRow}
                    closeWpsModal={this.closeWpsModal}
                    ref={node => {
                        this.headerNode = node;
                    }}
                />
                <div className='postseq-content'>
                    <TableInfo
                        {...componentProps}
                        ref={node => {
                            this.tableInfo = node;
                        }}
                    />
                </div>
                <WpsinitModal 
                    {...componentProps}
                    visible={wpsvisible}
                    onClose={this.closeWpsModal}
                    confirm={this.confirmOpenWps}
                    copySure={this.copySure}
                />
                <SettingModal
                    {...componentProps}
                    selectedRow={selectedRow}
                    visible={preSettingVisible}
                    onClose={this.onClose}
                />
            </div>
        );
    }
}

export default BasicArchiveBase;
